<template>
	<view class="map-container" :prop="info" :change:prop="mapModel.onChange" >
		<view class="goback" @click="gobak" :style="`top: ${statusBarHeight + 12}px`">
			<image class="goback-icon" src="https://oss.wanguocar.com.cn/wanguo/vms_wcl_system/images/goback-icon.png" />
		</view>
		<view id="container" class="map"></view>
		<view class="content">
			<view class="search-input-wrap">
				<view class="search-input">
					<input 
						type="text" 
						class="input" 
						placeholder="输入关键字选取地点" 
						autocomplete="off"
						:value="inputValue"
						@input="mapModel.inputSearchAction"
					 />
				</view>
				<view class="cancel-btn" v-if="inputValue" @click="mapModel.cancelKeyWord">取消</view>
			</view>
			<view class="search-list">
				<view 
					class="search-item" 
					v-for="(item, index) in searchList" 
					:key="`${item.id}-${index}`" 
					:data-item="item"
					@click="mapModel.selectSearch"
				>
					<view class="name">{{ item.name }}</view>
					<view class="address">{{ item.address }}</view>
					<image class="checked-icon" v-if="selectItem.id===item.id" src="https://oss.wanguocar.com.cn/wanguo/vms_wcl_system/images/checked-icon.png" />
				</view>
			</view>
		</view>
		<view class="btn-wrap">
			<view class="btn" :class="{'disabled-btn': !selectItem.id}" @click="submit">确定</view>
		</view>
	</view>
</template>
<script>
	import { cloneDeep } from "lodash";
	export default {
		data() {
			return {
				info: {},
				searchList: [],
				selectItem: {},
				inputValue: "",
				statusBarHeight: 0
			}
		},
		mounted() {
			this.statusBarHeight = uni.getSystemInfoSync()['statusBarHeight']

		},
		methods: {
			setSearchList(pois) {
				this.searchList = cloneDeep(pois)
			},
			onSelectItem(item) {
				this.selectItem = item
			},
			onKeyWords(keywords) {
				this.inputValue = keywords
			},
			submit() {
				this.$emit("change", this.selectItem)
				this.gobak()
				console.log(this.selectItem)
			},
			gobak() {
				uni.navigateBack({
					delta: 1
				});
			}
		}
	}
</script>
<script module="mapModel" lang="renderjs">
	import AMapLoader from '@amap/amap-jsapi-loader';
	import { cloneDeep } from "lodash";
	window._AMapSecurityConfig = {
		securityJsCode: '3204765d4469529c3b56910a94bff975' //你的安全秘钥
	}
	let lastTimestamp = 0
	
	export default {
		data() {
			return {
				map: null,
				AMap: null,
				mapInfo: {},
				isMoveSearchTool: true,
				isInputSearchTool: true,
				inputSearchTimeOut: null,
				lastSearchList: [],
				searchList: [],
			}
		},
		mounted() {
			this.initGdMaps()
		},
		methods: {
			onChange(newValue, oldValue, ownerInstance, instance) {
				this.ownerInstance = ownerInstance
			},
			initGdMaps() {
				if (this.AMap) return
				const _this = this
				AMapLoader.load({
					"key": "439ac54e015cff7e0c00335458361bc6", // 申请好的Web端开发者Key，首次调用 load 时必填
					"version": "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
					"plugins": ["AMap.Geolocation", "AMap.Geocoder", "AMap.PlaceSearch"],
					AMapUI: {
						version: '1.1',
						plugins:['overlay/SimpleMarker']
					}
				}).then((AMap) => {
					_this.AMap = AMap;
					_this.map = new AMap.Map('container', {
						zoom: 17,
						showIndoorMap: false, //隐藏地图自带的室内地图图层
						rotateEnable: true, // 地图是否可旋转
					});
					let geolocation = new AMap.Geolocation();
					geolocation.getCurrentPosition(function (status, result) {
						if (status == 'complete') {
							_this.mapInfo.longitude = result.position.lng;
							_this.mapInfo.latitude = result.position.lat;
							_this.mapInfo.address = result.formattedAddress;
							_this.map.setCenter([result.position.lng, result.position.lat]);//传入经纬度移动地图的方法
							_this.moveSearch()
						} else {
							_this.moveSearch()
							console.log('失败原因排查信息:' + result.message);
						}
					});
					_this.map.addControl(geolocation)
			
				}).catch(e => {
					console.log(e);
				})
			},
			moveSearch() {
				const _this = this
				AMapUI.loadUI(['misc/PositionPicker'], function (PositionPicker) {

					let positionPicker = new PositionPicker({
						mode: 'dragMap',//dragMap：拖拽地图，dragMarker：拖拽点
						map: _this.map,
						iconStyle:{//自定义外观
						   url:'https://oss.wanguocar.com.cn/wanguo/vms_wcl_system/images/position-picker.png',//图片地址
						   size:[48,48],  //要显示的点大小，将缩放图片
						   ancher:[24,40],//锚点的位置，即被size缩放之后，图片的什么位置作为选中的位置
						}
					});
			
					positionPicker.on('success', function (positionResult) {
						if(!_this.isMoveSearchTool) {
							_this.isMoveSearchTool = true
							return
						}
						if(positionResult.info==="OK") {
							let regeocode = positionResult.regeocode || {}
							let pois = regeocode.pois || []
							pois = pois.map((item)=> {
								item.longitude = item.location.lng;
								item.latitude = item.location.lat;
								return item
							})
							_this.lastSearchList = cloneDeep(pois)
							_this.searchList = cloneDeep(pois)
							_this.ownerInstance && _this.ownerInstance.callMethod('setSearchList', pois)
						}

					});
					positionPicker.start();
				});

			},
			inputSearchAction(e) {
				const _this = this
				if(!e) return
				_this.inputSearchTimeOut = setTimeout(function() {
					let keywords = e.detail.value
					_this.inputSearch(keywords)
					_this.ownerInstance && _this.ownerInstance.callMethod('onKeyWords', keywords)
				}, 500);
			},
			inputSearch(keywords) {
				const _this = this
				_this.isInputSearchTool = true
				if(!keywords) {
					_this.isInputSearchTool = false
					_this.searchList = cloneDeep(_this.lastSearchList)
					_this.ownerInstance && _this.ownerInstance.callMethod('setSearchList', _this.searchList)
					return
				}
				let autoOptions = {
					pageSize: 50
				}
				let placeSearch = new _this.AMap.PlaceSearch(autoOptions);
				placeSearch.search(keywords, (status, result)=> {
					if(!_this.isInputSearchTool) return
					if(result.info==="OK") {
						let poiList = result.poiList || {}
						let pois = poiList.pois || []
						pois = pois.map((item)=> {
							item.longitude = item.location.lng;
							item.latitude = item.location.lat;
							return item
						})
						_this.searchList = cloneDeep(pois)
						_this.ownerInstance && _this.ownerInstance.callMethod('setSearchList', pois)
					}
				})
			},
			selectSearch(e) {
				const _this = this
				let item = e.currentTarget.dataset.item
				_this.isMoveSearchTool = false
				_this.lastSearchList = cloneDeep(_this.searchList)
				_this.map.setCenter([item.longitude, item.latitude]);
				_this.ownerInstance && _this.ownerInstance.callMethod('onSelectItem', item)
			},
			cancelKeyWord() {
				const _this = this
				_this.inputSearch('')
				_this.ownerInstance && _this.ownerInstance.callMethod('onKeyWords', '')
			}
		}
	}
</script>

<style scoped lang="scss">
	.map-container {
		width: 100vw;
		height: 100vh;
		display: flex;
		flex-direction: column;
		overflow: hidden;
		.goback {
			position: absolute;
			top: 40rpx;
			left: 24rpx;
			width: 60rpx;
			height: 60rpx;
			background-color: rgba(0, 0, 0, .5);
			border-radius: 50%;
			display: flex;
			justify-content: center;
			align-items: center;
			z-index: 999;
			.goback-icon {
				width: 40rpx;
				height: 40rpx;
			}
		}
		.map {
			flex: 1;
			width: 100%;
		}
		.content {
			.search-input-wrap {
				display: flex;
				align-items: center;
				padding: 10px;
				.search-input {
					flex: 1;
					padding: 16rpx;
					border-radius: 10rpx;
					background: #ebebeb;
					.input {
						font-size: 28rpx;
					}
				}
				.cancel-btn {
					margin-left: 10rpx;
					color: #1989FA;
				}
			}
			
			.search-list {
				padding: 0 10px;
				height: 50vh;
				overflow: auto;
				.search-item {
					position: relative;
					padding: 10px 0;
					padding-right: 40px;
					cursor: pointer;
					border-bottom: 1px solid #dedede;
					.name {
						color: #333;
						font-size: 28rpx;
					}
					.address {
						color: #aaa;
						font-size: 24rpx;
					}
					.checked-icon {
						position: absolute;
						top: 50%;
						right: 24rpx;
						transform: translateY(-50%);
						width: 40rpx;
						height: 26rpx;
					}
				}
			}
		}
		.btn-wrap {
			height: 40px;
			padding: 4px 12px;
			box-shadow: 0 2px 20px rgba(0, 0, 0, .2);
			background-color: #fff;
			.btn {
				height: 40px;
				line-height: 40px;
				text-align: center;
				color: #fff;
				border-radius: 6px;
				background-color: #1989fa;
			}
			.disabled-btn {
			    background-color: #94d3fd;
			}
		}
	}
</style>
<style lang="scss">
	::v-deep .amap-logo {
		display: none!important;
	}
	::v-deep .amap-copyright {
		display: none!important;
	}
</style>